<template>
  <div class="app-container">

    <el-tabs v-model="activeName">
      <!-- 订单设置 -->
      <el-tab-pane
        label="订单设置"
        name="订单设置"
      >
        <el-card>
          <el-form
            label-position="top"
            label-width="100px"
            :model="form"
            label-suffix=":"
            :rules="rules"
            class="orderSetting"
            ref="orderForm"
          >
            <el-form-item
              prop="waitPayOrderCloseMinute"
              label="待支付订单关闭时间（分钟）"
              class="waitPayItem"
            >
              <el-input-number
                :min="0"
                controls-position="right"
                v-model="form.waitPayOrderCloseMinute"
                name="waitPayOrderCloseMinute"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              prop="waitEvaluateGoodDay"
              label="待评价自动默认好评时间（天）"
              class="waitComentItem"
            >
              <el-input-number
                :min="0"
                controls-position="right"
                v-model="form.waitEvaluateGoodDay"
                name="waitEvaluateGoodDay"
              ></el-input-number>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card
          style="margin-top: 20px"
          :body-style="[{ 'padding-left': '40px' }]"
        >
          <el-button @click="cancel">取消</el-button>
          <el-button
            type="primary"
            @click="submit"
          >确定</el-button>
        </el-card>
      </el-tab-pane>

      <!-- 退款设置 -->
      <el-tab-pane
        label="退款设置"
        name="退款设置"
      >
        <!-- 寄件人信息 -->
        <el-card style="margin-bottom: 20px; padding:0px">
          <el-form
            :model="orderSettingForm"
            label-position="top"
            label-width="100px"
            label-suffix=":"
            :rules="orderSettingRules"
            ref="refundForm"
          >
            <div style="font-weight:bold;padding:0 0 10px 0;border-bottom:1px solid #eee">寄件人信息</div>
            <dk-form
              :form-input="orderSettingFormList"
              :span-num="1"
              :rule-form="orderSettingForm"
            >
            <template #senderArea="row">
              <!-- <el-form-item
                label="收货地址"
                prop="senderArea"
              > -->
              <div style="display: flex;gap:8px">
                <el-select
                  v-model="orderSettingForm.senderProvince"
                  placeholder="请选择省"
                  @change="citySelectHandle('senderProvince')"
                >
                  <el-option
                    v-for="item in addressList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="orderSettingForm.senderCity"
                  :disabled="!orderSettingForm.senderProvince"
                  placeholder="请选择市"
                  @change="citySelectHandle('senderCity')"
                >
                  <el-option
                    v-for="item in theCity"
                    :key="item.code"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="orderSettingForm.senderArea"
                  :disabled="!orderSettingForm.senderCity"
                  placeholder="请选择区"
                >
                  <el-option
                    v-for="item in theArea"
                    :key="item.code"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </div>
              <!-- </el-form-item> -->
            </template>
            </dk-form>
          </el-form>
        </el-card>

        <el-card
          style="margin-top: 20px"
          :body-style="[{ 'padding-left': '40px' }]"
        >
          <el-button @click="cancel">取消</el-button>
          <el-button
            type="primary"
            @click="submit"
          >确定</el-button>
        </el-card>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>
<script>
// 接口api：first step
import {
  getCities,
  getProvince,
  getOrderSetting,
  getArea,
  setOrderSetting,
  getOrderSettingInfo,
} from "@/api/merchant-order-manage/order-setting";
import addressList from "@/components/CityPicker/cityData.js";

export default {
  data() {
    return {
      // 城市选择
      addressList,
      // 当前激活的tab
      activeName: "订单设置",
      // 选中的商品类型
      loading: false,
      // 表单对象：two step
      form: {
        waitPayOrderCloseMinute: 30,
        waitEvaluateGoodDay: 15,
      },

      // 校验对象：four step
      rules: {
        waitPayOrderCloseMinute: [
          {
            required: true,
            message: "请输待支付订单关闭时间",
            trigger: "change",
          },
        ],
        waitEvaluateGoodDay: [
          {
            required: true,
            message: "请输入待评价自动默认好评时间",
            trigger: "change",
          },
        ],
      },
      // 订单设置 - 寄件人信息表单对象
      orderSettingForm: {
        senderArea: "",
        senderName: "",
        senderPhone: "",
        // 选择器选中的省、市、区
        senderProvince: "",
        senderCity: "",
        senderArea: "",
        senderAddress: "",
        senderZipCode: "",
      },
      orderSettingFormList: [
        {
          label: "收货人",
          placeholder: "请输入",
          type: "input",
          name: "senderName",
          prop: "senderName",
          maxlength: 30,
        },
        {
          label: "联系电话",
          placeholder: "请输入",
          type: "input",
          name: "senderPhone",
          prop: "senderPhone",
          maxlength: 30,
        },
        {
          label: "收货地址",
          placeholder: "请输入",
          type: "slot",
          name: "senderArea",
          prop: "senderArea",
        },
        {
          label: "详细地址",
          placeholder: "请输入",
          type: "input",
          name: "senderAddress",
          prop: "senderAddress",
        },
        {
          label: "邮编",
          placeholder: "请输入",
          type: "input",
          name: "senderZipCode",
          prop: "senderZipCode",
        },
      ],
      // 订单设置 - 寄件人信息表单校验对象
      orderSettingRules: {
        senderName: [
          { required: true, message: "请输入收货人姓名", trigger: "change" },
        ],
        senderPhone: [
          {
            required: true,
            message: "请输入收货人联系电话",
            trigger: "change",
          },
          {
            min: 11,
            max: 11,
            message: "请输入11位数的电话号码",
            trigger: "blur",
          },
        ],
        senderArea: [
          {
            required: true,
            message: "请选择地区",
            trigger: "blur",
          },
        ],
        senderAddress: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "change",
          },
        ],
        senderZipCode: [
          {
            required: true,
            message: "请输入邮编",
            trigger: "change",
          },
          { required: true, message: "请输入邮编", trigger: "blur" },
          { pattern: /^[1-9][0-9]{5}$/, message: '请输入正确的邮编', trigger: 'blur' }
        ],
      },
      // 接口存储对象：five step
      interfaceObj: {
        provApiName: getProvince,
        cityApiName: getCities,
        areaApiName: getArea,
        getApiName: getOrderSettingInfo,
      },
    };
  },
  created() {
    // 获取数据
    this.network().getList();
  },
  methods: {
    citySelectHandle(area) {
      switch (area) {
        case "senderProvince":
          this.orderSettingForm.senderCity = "";
          this.orderSettingForm.senderArea = "";
          break;
        case "senderCity":
          this.orderSettingForm.senderArea = "";
          break;
      }
    },

    cancel() {
      this.$router.go(-1);
    },
    submit() {
      const throttleStatus = this.throttle(); // 节流
      if (!throttleStatus) return;
      Promise.all([
        this.$refs["orderForm"].validate(),
        this.$refs["refundForm"].validate(),
      ])
        .then((res) => {
          this.network().setForm(this.form, this.orderSettingForm);
        })
        .catch((err) => {
          this.$message({
            message: "请填写完整",
            type: "error",
          });
          return false;
        });
    },
    network() {
      return {
        // 获取数据
        getList: async () => {
          const { getApiName } = this.interfaceObj;
          const { data, code } = await getApiName();
          if (code === 0) {
            // Object.assign(this.form, data, {
            //   sendPointConsumeType: data.sendPointConsumeType ? data.sendPointConsumeType.split(',') : this.form.sendPointConsumeType
            // });
            // Object.assign(this.orderSettingForm, data);
            for (let item in data) {
              // 有自己对象都赋值
              if (this.form.hasOwnProperty(item)) {
                this.form[item] = data[item];
              }
              if (this.orderSettingForm.hasOwnProperty(item)) {
                this.orderSettingForm[item] = data[item];
              }
            }
          }
        },
        // 提交数据
        setForm: async () => {
          console.log(this.form);
          const obj = {
            ...this.form,
            ...this.orderSettingForm,
            updateBy: this.$store.state.user.name,
          };
          console.log(obj);
          const { code, msg } = await setOrderSetting(obj);
          if (code === 0) {
            this.activeName = "订单设置";
            this.network().getList();
            return this.$message({
              message: msg,
              type: "success",
            });
          }
          this.$message({
            message: msg,
            type: "error",
          });
        },
      };
    },
    click() {
      return {};
    },
  },
  computed: {
    theCity() {
      return this.addressList.find(
        (item) => item.name === this.orderSettingForm.senderProvince
      )?.children;
    },
    theArea() {
      return (
        this.addressList
          .find((item) => item.name === this.orderSettingForm.senderProvince)
          ?.children.find(
            (item) => item.name === this.orderSettingForm.senderCity
          )?.children || []
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.app-container {
  background-color: #f0f2f5;
}
.waitPayItem {
  position: relative;
  &:after {
    content: "待支付订单关闭时间（分钟）";
    position: absolute;
    top: 9px;
    left: 207px;
    color: #999;
    font-size: 12px;
  }
}
.waitComentItem {
  position: relative;
  &:after {
    content: "订单完成后X天用户未评价，系统自动默认订单五星好评";
    position: absolute;
    top: 9px;
    left: 220px;
    color: #999;
    font-size: 12px;
  }
}
.pointInput {
  display: flex;
  flex-direction: row;
  ::v-deep.el-input__inner {
    width: 100px;
  }
}
::v-deep.el-input-number--medium {
  width: 400px;
}
</style>